using System.Web;

namespace AUSRIS.Reports.Extensions.Security.Authentication
{
	public static class HttpClientCertificateUtility
	{
		/// <summary>
		/// Gets the CommonName (CN) value from the client certificate
		/// </summary>
		public static string GetCommonName(HttpClientCertificate httpClientCertificate)
		{
			string[] parts = httpClientCertificate.Subject.Split(',');
			foreach ( string part in parts )
			{
				if ( part.Trim().StartsWith("CN=") )
				{
					return part.Trim().Remove(0, 3);
				}
			}
			return string.Empty;
		}

		/// <summary>
		/// Gets the First Name from the client certificate.
		/// </summary>
		/// <remarks>
		/// Assumes the Common name is in the format of FIRSTNAME.LASTNAME[...]
		/// </remarks>
		public static string GetFirstName(HttpClientCertificate httpClientCertificate)
		{
			string commonName = GetCommonName(httpClientCertificate);
			string[] parts = commonName.Split('.');
			if ( parts.Length > 0 )
			{
				return parts[0];
			}
			else
			{
				return string.Empty;
			}
		}

		/// <summary>
		/// Gets the Last Name from the client certificate
		/// </summary>
		/// <remarks>
		/// Assumes the Common name is in the format of FIRSTNAME.LASTNAME[...]
		/// </remarks>
		public static string GetLastName(HttpClientCertificate httpClientCertificate)
		{
			string commonName = GetCommonName(httpClientCertificate);
			string[] parts = commonName.Split('.');
			if ( parts.Length > 1 )
			{
				return parts[1];
			}
			else
			{
				return string.Empty;
			}
		}
	}
}